package com.example.nacosconsumer.Controller;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.logging.Logger;

/**
 * 构造一个拦截器
 */
@Component
public class LoginHandlerInterceptor implements HandlerInterceptor {
    Logger logger = Logger.getLogger("拦截器");
    //目标方法执行之前
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception{
        //当在未登录的情况下访问其他页面时Session在此处被创建
        //从securityContext中获取当前用户的用户名
        SecurityContext context = SecurityContextHolder.getContext();
        Authentication authentication = context.getAuthentication();
        String user = authentication.getName();

        if(user!=null){
            //已经登录
            logger.info("拦截器显示已经是登录状态");
            //System.out.println("当前登录用户数量:"+request.getSession().getAttribute("count"));

            return true;
        }
        logger.info("一条请求被拦截");
        //登录失败时销毁Session
        request.getSession().invalidate();
        request.getRequestDispatcher("/login").forward(request,response);
        return false;
    }
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
